package com.ktjiaoyu.controller;

import com.ktjiaoyu.entity.SysUser;
import com.ktjiaoyu.service.SysUserService;
import com.ktjiaoyu.utils.Constants;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.view.UrlBasedViewResolver;

@Controller
public class LoginController extends BaseController{
    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private HttpServletRequest request;

    //获取request对象
    public HttpServletRequest request() {
//        return ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
        return request;
    }

    //获取session对象
    public HttpSession session() {
        return request().getSession();
    }

    //负责转发到任意路径
    public String forward(String url) {
        return UrlBasedViewResolver.FORWARD_URL_PREFIX + url;
    }

    //负责重定向任意路径
    public String redirect(String url) {
        return UrlBasedViewResolver.REDIRECT_URL_PREFIX + url;
    }

    @GetMapping("/login")
    public String toLogin() {
        return redirect("/login.jsp");
    }

    @PostMapping("/login")
    public String login(@RequestParam("account") String account, @RequestParam("password") String password){
        SysUser loginUSer = sysUserService.login(account, password);
        if (loginUSer != null){
            //登录成功
            session(Constants.SESSION_USER, loginUSer);
            //重定向返回首页
            return redirect("/main/index");
        }else {
            //登录失败
//            request(Constants.REQUEST_ERROR, "用户名或密码错误");
//            return forward("/login.jsp");
            throw new RuntimeException("登录失败：用户名或密码错误");
        }
    }

    @GetMapping("/ex")
    public String throwException() {
        throw new RuntimeException("测试不同异常映射到不同页面");
    }

    @GetMapping("/nodb")
    public String noDB() {
        throw new RuntimeException("测试数据库异常映射到不同页面");
    }

    @GetMapping("/main/index")
    public String index() {
        return "index";
    }

    //退出登录
    @GetMapping("/logout")
    public String logout(HttpSession session) {
        // 销毁当前用户的session
        session.invalidate();
        // 重定向到登录页面
        return redirect("/login");
    }

//    @ExceptionHandler(value = RuntimeException.class)
//    public String handleException(RuntimeException e, HttpServletRequest request) {
//        //设置捕获错误对象到request作用域
//        request.setAttribute(Constants.REQUEST_ERROR, e);
//        return "500";
//    }
}
